package com.chengjj.kings.core.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.chengjj.kings.config.properties.AppNameProperties;
import com.chengjj.kings.core.model.exception.CoreExceptionEnum;
import com.chengjj.kings.core.model.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;

/**
 * @Author: 成俊杰
 * @CreateDate: 2019/3/8
 * @Version: 1.0
 * @Description: 高频方法集合类
 */
public class ToolUtil extends ValidateUtil {
    public static final int SALT_LENGTH = 6;

    public ToolUtil() {
    }

    /**
     * 获取指定长度随机字符串
     *
     * @param length 长度
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * md5加密
     *
     * @param password 密码
     * @param salt     盐
     * @return
     */
    public static String md5Hex(String password, String salt) {
        return md5Hex(password + salt);
    }

    public static String md5Hex(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(str.getBytes());
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < bs.length; i++) {
                if (Integer.toHexString(255 & bs[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(255 & bs[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(255 & bs[i]));
                }
            }
            return md5StrBuff.toString();

        } catch (Exception e) {
            throw new ServiceException(CoreExceptionEnum.ENCRYPT_ERROR);
        }
    }

    /**
     * 去掉字符串中空格
     *
     * @param value
     * @return
     */
    public static String removeWhiteSpace(String value) {
        return isEmpty(value) ? "" : value.replaceAll("\\s*", "");
    }

    /**
     * 获取与当前时间相差几分钟的时间
     *
     * @param seconds
     * @return
     */
    public static String getCreateTimeBefore(int seconds) {
        long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
        Date date = new Date(currentTimeInMillis - (long) (seconds * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 获取异常信息
     *
     * @param e
     * @return
     */
    public static String getExceptionMsg(Throwable e) {
        StringWriter sw = new StringWriter();
        try {
            e.printStackTrace(new PrintWriter(sw));
        } finally {
            try {
                sw.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return sw.getBuffer().toString().replaceAll("\\$", "T");
    }

    /**
     * 获取应用名称
     *
     * @return
     */
    public static String getApplicationName() {
        try {
            AppNameProperties bean = SpringContextHolder.getBean(AppNameProperties.class);
            return bean != null ? bean.getName() : "";
        } catch (Exception var2) {
            Logger logger = LoggerFactory.getLogger(ToolUtil.class);
            logger.error("获取应用名称错误", var2);
            return "";
        }
    }

    /**
     * 获取IP
     *
     * @return
     */
    public static String getIP() {
        try {
            StringBuilder IFCONFIG = new StringBuilder();
            Enumeration en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                Enumeration enumIpAddr = intf.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                        IFCONFIG.append(inetAddress.getHostAddress().toString() + "\n");
                    }
                }
            }
            return IFCONFIG.toString();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
                return null;
            }
        }
    }

    /**
     * 对象复制
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target) {
        BeanUtil.copyProperties(source, target, CopyOptions.create().setIgnoreNullValue(true));
    }

    /**
     * 判断当前是否为windows系统
     *
     * @return
     */
    public static Boolean isWinOS() {
        String os = System.getProperty("os.name");
        return os.toLowerCase().startsWith("win") ? true : false;
    }

    /**
     * 获取操作系统缓存的临时目录
     *
     * @return
     */
    public static String getTemPath() {
        return System.getProperty("java.io.tmdir");
    }

    /**
     * 对象转换成Int
     *
     * @param val
     * @return
     */
    public static Integer toInt(Object val) {
        if (val instanceof Double) {
            BigDecimal bigDecimal = new BigDecimal((Double) val);
            return bigDecimal.intValue();
        } else {
            return Integer.valueOf(val.toString());
        }
    }

    /**
     * 判断是否为数字
     *
     * @param obj
     * @return
     */
    public static boolean isNum(Object obj) {
        try {
            Integer.parseInt(obj.toString());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取文件的 路径
     *
     * @param filePath
     * @return
     */
    public static String getWebRootPath(String filePath) {
        try {
            String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath();
            path = path.replace("/WEB-INF/classes/", "");
            path = path.replace("/target/classes", "");
            path = path.replace("file:/", "");
            return isEmpty(filePath) ? path : path + "/" + filePath;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取文件后缀名
     *
     * @param fileWholeName
     * @return
     */
    public static String getFileSuffix(String fileWholeName) {
        if (isEmpty(fileWholeName)) {
            return "none";
        } else {
            int lastIndexOf = fileWholeName.lastIndexOf(".");
            return fileWholeName.substring(lastIndexOf + 1);
        }
    }

    /**
     * 获取时间
     *
     * @param o
     * @return
     */
    public static String dateType(Object o) {
        return o instanceof Date ? DateUtil.formatDate((Date) o) : o.toString();
    }

    /**
     * 获取当前时间Time
     *
     * @return
     */
    public static String currentTime() {
        return DateUtil.formatDateTime(new Date());
    }
}
